package com.cn.cash.baselib.util;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import android.webkit.MimeTypeMap;

import com.cn.cash.baselib.BaseManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by CN on 2016/9/22.
 */
public class CNUtil {
    public static void log(String msgLog) {
        if (BaseManager.isIsDebugMode()) {
            Log.v("CN", "========================");
            Log.v("CN", msgLog);
        }
    }

    public static void openFile(Context context, String filePath) {
        Intent intent = new Intent();
        File file = new File(filePath);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//设置标记
        intent.setAction(Intent.ACTION_VIEW);//动作，查看
        intent.setDataAndType(Uri.fromFile(file), getMimeType(filePath));//设置类型
        context.startActivity(intent);
    }

    public static MultipartBody.Part prepareFilePart(String partName, String path) {
        try {
            File file = new File(path);
            if (file.exists()) {
                String mimeType = getMimeType(path);
                log("mimeType:" + mimeType);
                RequestBody requestFile =
                        RequestBody.create(MediaType.parse(mimeType), file);
                return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getFileExtensionFromUrl(String filePath) {
        return MimeTypeMap.getFileExtensionFromUrl(filePath);
    }

    // 根据文件后缀名获得对应的MIME类型。
    public static String getMimeType(String filePath) {
        try {
            String ext = MimeTypeMap.getFileExtensionFromUrl(filePath);
            String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);
            if (mimeType == null) {
                mimeType = "*/*";
            }
            return mimeType;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "*/*";
    }

    /**
     * 是否有网络连接
     *
     * @return
     */
    public static boolean isNetworkConnected() {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) BaseManager.getApplication()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        if (mNetworkInfo != null) {
            return mNetworkInfo.isConnected();
        }
        return false;
    }

    public static boolean isWifiConnected() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            ConnectivityManager connMgr = (ConnectivityManager) BaseManager.getApplication().getSystemService(Context
                    .CONNECTIVITY_SERVICE);
            NetworkInfo wifiNetworkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (wifiNetworkInfo != null) {
                return wifiNetworkInfo.isConnected();
            }
        } else {
            ConnectivityManager connMgr = (ConnectivityManager) BaseManager.getApplication().getSystemService(Context
                    .CONNECTIVITY_SERVICE);
            Network[] networks = connMgr.getAllNetworks();
            for (int i = 0; i < networks.length; i++) {
                NetworkInfo networkInfo = connMgr.getNetworkInfo(networks[i]);
                if (networkInfo != null) {
                    if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                        return networkInfo.isConnected();
                    }
                }
            }
        }
        return false;
    }

    public static int getDeviceWidth(Activity activity) {
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;// 宽度
    }

    public static int getDeviceHeight(Activity activity) {
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.heightPixels;// 高度
    }

    public static int getScreenWidth() {
        WindowManager wm = (WindowManager) BaseManager.getApplication().getApplicationContext()
                .getSystemService(Context.WINDOW_SERVICE);

        return wm.getDefaultDisplay().getWidth();
    }

    public static int getScreenHeight() {
        WindowManager wm = (WindowManager) BaseManager.getApplication().getApplicationContext()
                .getSystemService(Context.WINDOW_SERVICE);

        return wm.getDefaultDisplay().getHeight();
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(float dpValue) {
        final float scale = BaseManager.getApplication().getApplicationContext().getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(float pxValue) {
        final float scale = BaseManager.getApplication().getApplicationContext().getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }


    /**
     * *******************
     * bitmap转byte数组
     *
     * @param bmp
     * @param needRecycle
     * @return *******************
     */
    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    public static HashMap<String, String> json2HashMap(String json) {
        HashMap<String, String> data = new HashMap<String, String>();
        // 将json字符串转换成jsonObject
        try {
            JSONObject jsonObject = new JSONObject(json);
            Iterator it = jsonObject.keys();
            // 遍历jsonObject数据，添加到Map对象
            CNUtil.log("jsonObject:" + jsonObject);
            while (it.hasNext()) {
                String key = String.valueOf(it.next());
                String value = jsonObject.get(key) == null ? "" : jsonObject.getString(key);
                data.put(key, value);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return data;
    }

    /**
     * ******************
     * 获取版本号(内部识别号)
     *
     * @return ******************
     */
    public static int getVersionCode() {
        try {
            PackageInfo pi = BaseManager.getApplication().getPackageManager()
                    .getPackageInfo(BaseManager.getApplication().getPackageName(), 0);
            return pi.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * ******************
     * 获取版本名称
     */
    public static String getVersionName() {
        try {
            PackageInfo pi = BaseManager.getApplication().getPackageManager()
                    .getPackageInfo(BaseManager.getApplication().getPackageName(), 0);
            return pi.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    // 字符串截断
    public static String getLimitString(String source, int length) {
        if (null == source) {
            return "";
        } else if (source.length() > length) {
            return source.substring(0, length).replace('\n', ' ') + "...";
        } else {
            return source.replace('\n', ' ');
        }
    }


    public static boolean isServiceWork(Context mContext, String serviceName) {
        boolean isWork = false;
        ActivityManager myAM = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> myList = myAM.getRunningServices(1000);
        if (myList.size() <= 0) {
            return false;
        }
        for (int i = 0; i < myList.size(); i++) {
            ComponentName componentName = myList.get(i).service;
            String mName = componentName.getClassName().toString();
            if (mName.equals(serviceName)) {
                isWork = true;
                break;
            }
        }
        return isWork;
    }


    public static boolean isValidConnect() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            //获得ConnectivityManager对象
            ConnectivityManager connMgr = (ConnectivityManager) BaseManager.getApplication().getSystemService(Context
                    .CONNECTIVITY_SERVICE);
            //获取ConnectivityManager对象对应的NetworkInfo对象
            //获取WIFI连接的信息
            NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
            if (networkInfo != null) {
                if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                    return networkInfo.isConnected();
                } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                    return networkInfo.isConnected();
                }
            }
            return false;
            //API大于23时使用下面的方式进行网络监听
        } else {
            //获得ConnectivityManager对象
            ConnectivityManager connMgr = (ConnectivityManager) BaseManager.getApplication().getSystemService(Context
                    .CONNECTIVITY_SERVICE);

            //获取所有网络连接的信息
            Network[] networks = connMgr.getAllNetworks();
            //通过循环将网络信息逐个取出来
            boolean isWifiConnected = false;
            for (int i = 0; i < networks.length; i++) {
                //获取ConnectivityManager对象对应的NetworkInfo对象
                NetworkInfo networkInfo = connMgr.getNetworkInfo(networks[i]);
                if (networkInfo != null) {
                    if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                        isWifiConnected = networkInfo.isConnected();
                        break;
                    } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                        isWifiConnected = networkInfo.isConnected();
                        break;
                    }
                }
            }
            return isWifiConnected;
        }
    }

    //获取应用设置界面Intent
    public static Intent getAppSettingIntent() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", BaseManager.getApplication().getPackageName(), null);
        intent.setData(uri);
        return intent;
    }
}